package com.atguigu.gmall.realtime.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author Felix
 * @date 2023/8/10
 * 操作Redis的工具类
 */
public class RedisUtil {
    private static JedisPool jedisPool;
    static {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMinIdle(5);
        jedisPoolConfig.setMaxIdle(5);
        jedisPoolConfig.setMaxTotal(100);
        jedisPoolConfig.setBlockWhenExhausted(true);
        jedisPoolConfig.setMaxWaitMillis(2000L);
        jedisPoolConfig.setTestOnBorrow(true);

        jedisPool = new JedisPool(jedisPoolConfig,"hadoop102",6379,10000);
    }
    //获取Jedis客户端
    public static Jedis getRedisClient(){
        System.out.println("~~~获取Jedis客户端~~~");
        Jedis jedis = jedisPool.getResource();
        return jedis;
    }
    //关闭Jedis客户端
    public static void closeRedisClient(Jedis jedis){
        if(jedis != null){
            System.out.println("~~~关闭Jedis客户端~~~");
            jedis.close();
        }
    }

    //获取一个线程安全的可以发送异步请求的Redis客户端连接
    public static StatefulRedisConnection<String,String> getAsyncRedisConnection(){
        // 连接到 redis 的4号库
        RedisClient redisClient = RedisClient.create("redis://hadoop102:6379/0");
        return redisClient.connect();
    }

    //关闭异步请求的Redis客户端
    public static void closeAsyncRedisConnection(StatefulRedisConnection<String,String> redisConn){
        if(redisConn != null && redisConn.isOpen()){
            System.out.println("~~~关闭异步Redis连接~~~");
            redisConn.close();
        }
    }

    //从Redis中异步的查询维度数据
    public static JSONObject asyncGetDimInfo(StatefulRedisConnection<String,String> redisConn,String redisKey){
        RedisAsyncCommands<String, String> asyncCommands = redisConn.async();
        try {
            String dimStrInfo = asyncCommands.get(redisKey).get();
            if(StringUtils.isNotEmpty(dimStrInfo)){
                JSONObject dimJsonObj = JSON.parseObject(dimStrInfo);
                return dimJsonObj;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //以异步的方式向Redis放维度数据
    public static void asyncWriteDimInfo(StatefulRedisConnection<String,String> redisConn,
                                         String redisKey,JSONObject dimJsonObj){
        RedisAsyncCommands<String, String> asyncCommands = redisConn.async();
        asyncCommands.setex(redisKey,3600*24,dimJsonObj.toJSONString());
    }



    public static void main(String[] args) {
        System.out.println(asyncGetDimInfo(getAsyncRedisConnection(), "dim_sku_info:17"));
    }
}
